#pragma once
#include<iostream>
#include<vector>
#include"IntAddr.hpp"
#include"Log.hpp"
#include"Mutex.hpp"

using namespace MyMutex;
using namespace MyLog;

class Route
{
private:
    bool IsExit(InetAddr &peer)
    {
        for(auto &user:_online_client)
        {
            if(user == peer)
                return true;
        }
        return false;
    }

    void AddUser(InetAddr &peer)
    {
        LOG(Loglevel::INFO) << "新增一个在线用户: " << peer.GetString();
        _online_client.push_back(peer);
    }

    void DelUser(InetAddr &peer)
    {
        for(auto iter = _online_client.begin();iter!=_online_client.end();iter++)
        {
            if(*iter == peer)
            {
                LOG(Loglevel::INFO) << "删除一个在线用户: "<< peer.GetString() << " 成功"; 
                _online_client.erase(iter);
                break;
            }
        }
    }
public:
    Route()
    {}

    void MsgRoute(int sockfd,const std::string &msg,InetAddr &peer)
    {
        LockGuard lock(_mutex);

        if(!IsExit(peer))
        {
            AddUser(peer);
        }
        std::string sendmsg = peer.GetString() + ": " + msg;
        for(auto &user:_online_client)
        {
            sendto(sockfd,sendmsg.c_str(),sendmsg.size(),0,(const struct sockaddr*)&user.GetSockaddr_in(),sizeof (user.GetSockaddr_in()));
        }

        if(msg == "quit")
        {
            LOG(Loglevel::INFO) << "删除一个用户: " << peer.GetString();
            DelUser(peer);
        }
    }

    ~Route()
    {}
private:
    std::vector<InetAddr> _online_client;

    Mutex _mutex;
};